package com.example.day03

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.day03.databinding.ActivityReginBinding
import com.example.day03.login.ReginViewModel
import com.example.day03.mvvm.BaseActivity
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ReginActivity : BaseActivity<ActivityReginBinding,ReginViewModel>() {
    override fun bindLayoutId(): Int {
        return R.layout.activity_regin
    }

    override fun getViewModel(): Class<ReginViewModel> {
        return ReginViewModel::class.java
    }

    override fun initView() {
        binding.hq.isEnabled=false
        binding.phone.addTextChangedListener(object:TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (RegexUtils.isMobileExact(binding.phone.text.toString())){
                    binding.hq.isEnabled=true
                }else{
                    binding.hq.isEnabled=false
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        binding.hq.setOnClickListener {
            binding.hq.isEnabled=false
            lifecycleScope.launch {
                for (i in 5 downTo 0){
                    binding.hq.text="${i}秒后重新获取"
                    delay(1000)
                    binding.hq.text="重新获取"
                }
                binding.hq.isEnabled=true
            }
            viewModel.getCode(binding.phone.text.toString())
        }
        binding.zc.setOnClickListener {
            if (binding.phone.text.toString().isNullOrEmpty()||binding.pass1.text.toString().isNullOrEmpty()||binding.pass2.text.toString().isNullOrEmpty()){
                ToastUtils.showLong("不能为空")
                return@setOnClickListener
            }
            if (binding.pass1.text.toString()!=binding.pass2.text.toString()){
                ToastUtils.showLong("两次密码不一样")
                return@setOnClickListener
            }
            viewModel.getRegin(binding.phone.text.toString(),binding.yzm.text.toString())
        }
    }

    override fun initDate() {
        viewModel.codesuccess.observe(this){
            if (it.code==200){
                binding.yzm.setText(it.data.content)
            }
        }
        viewModel.reginsuccess.observe(this){
            if (it.code==200){
                startActivity(Intent(this@ReginActivity,LoginActivity::class.java)
                    .putExtra("phone",binding.phone.text.toString())
                    .putExtra("pwd",binding.pass1.text.toString()))
            }
            ToastUtils.showLong(it.message)
        }
    }

}